import React, { useEffect, useRef, useState } from "react";
import "./HeroCom.css";
import axios from "axios";
import { Link, useNavigate } from "react-router-dom";

export default function HeroCom() {
  //声明状态
  let [heros, setHeros] = useState([]);
  //声明状态 文本框输入内容的值
  let [keyword, setKeyword] = useState('');
  //创建 ref 容器
  let input = useRef();
  //声明状态表示是否正在请求中....
  let [isLoading, setIsLoading] = useState(false);
  //组件挂载完毕
  useEffect(() => {
    let getData = async () => {
      //更新 isLoading 状态
      setIsLoading(true);
      //清空英雄列表
      setHeros([]);
      //发送 AJAX 请求
      let response = await axios.get("http://api.xiaohigh.com/heros", {
        params: {
          name_like: keyword
        }
      });
      //更新状态
      setHeros(response.data);
      //更新 isLoading 状态
      setIsLoading(false);
    };
    getData();
  }, [keyword]);
  
  //声明 search 函数 按钮的单击事件处理程序
  let search = async () => {
    //获取文本框中输入的关键字
    let keyword = input.current.value;//张
    //更新状态
    setKeyword(keyword);
  }

  //获取跳转函数
  let nav = useNavigate();

  //声明forward函数
  let forward = () => {
    nav(1);
  }

  return (
    <div className="hero-container">
      <button className="btn btn-primary btn-sm" onClick={forward}>前进</button>
      <h2>欢迎来到王者荣耀</h2>
      <hr />
      <div className="form-section">
        <input type="text" ref={input} />
        <button onClick={search}>搜索</button>
      </div>
      <hr />
      <div className="hero-list">
        {heros.map((item) => {
          return (
            <div className="hero-item" key={item.id}>
              <img
                width="100%"
                src={`http://cdn.xiaohigh.com${item.image}`}
                alt=""
                onClick={() => {
                  //调用函数 实现路由跳转 params
                  // nav(`/hero/${item.id}`);
                  //query
                  // nav(`/hero?id=${item.id}`);
                  //state传参
                  nav('/hero', {
                    // 设置 state 参数
                    state: {
                      id: item.id
                    },
                    //设置替换模式  location.replace()
                    replace: false
                  })
                }}
              />
              <div className="name">{item.name}</div>
            </div>
          );
        })}

        {heros.length === 0 && !isLoading && <h2 className="center">暂无数据</h2>}
        
        {isLoading && <h2 className="center">加载中....</h2>}
      </div>
    </div>
  );
}
